package icu.lookyousmileface.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author starrysky
 * @title: ShiroController
 * @projectName spring-shiro-parent
 * @description: controller layer
 * @date 2021/2/1021:07
 */
@Controller
public class ShiroController {
    /**
     * 用于首页的跳转
     * @param map
     * @return
     */
    @GetMapping({"/","/index"})
    public String index(ModelMap map){
        map.addAttribute("msg","Hello shiro!");
        return "index";
    }

    /**
     * 用于add、update页面的跳转
     * @return
     */
    @GetMapping("/user/{fowUrl}")
    public String toTwoPages(@PathVariable("fowUrl")String urlInfo,ModelMap map){
        map.addAttribute("msg",urlInfo);
        return "user/"+urlInfo;
    }

    /**
     * 跳到登陆页面
     * @return
     */
    @GetMapping("/toLogin")
    public String loginPages(){
        return "login";
    }

    /**
     * 用户表单数据提交
     * @return
     */
    @PostMapping("/login")
    public String login(String username,String password,ModelMap modelMap){
//        获取登陆数据
        Subject subject = SecurityUtils.getSubject();
//        封装用户的登陆数据
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);

        try{
            subject.login(usernamePasswordToken);
            return "index";
        }catch (UnknownAccountException e){
            modelMap.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){
            modelMap.addAttribute("msg","密码错误");
            return "login";
        }
    }

    /**
     * 未经授权的页面
     * @return
     */
    @GetMapping("/authorizedPage")
    @ResponseBody
    public String authorized(){
        return "未经授权无法达到";
    }
}
